package ModelLayer;
import java.util.ArrayList;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;


/**
 * Write a description of class AdresseBog here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */

public class AdressBook implements Serializable
{
    // instance variables - replace the example below with your own
     ArrayList<Person> persons;
    
    private static AdressBook _instance = null; 
        
    public static AdressBook getInstance() {
      if(null == _instance) {
         _instance = new AdressBook();
      }
      return _instance;
    }
    
    /**
     * Constructor for objects of class AdresseBog
     */
   
         
     
     public AdressBook()
    {
        // initialise instance variables
        persons = new ArrayList<Person>();
    }

   
    public void addPerson(Person person)
    {
        persons.add(person);
    }
   
    public void removePerson(Person person)
    {
        persons.remove(person);
    }
    
    public void addPerson(int id, String name, String address, String postalCode, String city, String phoneNumber)
    {
        Person person = new Person(id, name, address, postalCode, city, phoneNumber);
        persons.add(person);
    }
    
    public ArrayList<Person> getPersons()
    {
        return persons;
    }
    
    public int getSize()
    {
        return persons.size();
    }
   
   
    public void printWholeAddressBook()
        {
            System.out.println("Addressbook entries: ");
        for (Person person : persons)
        {
            System.out.println(person.getName());
        }
       
    }
    
     public Person findPerson(String name)
    {
        Person person = null;      
        int index = 0;     
        boolean found = false; 
        while(index < persons.size() && !found)
        {
            person = persons.get(index); 
            if(person.getName().equals(name))
            {
                found = true;
            }
            else{
                 index++;  
                }
         } 
        if (found){
            return persons.get(index);
        }
        else{   
         return null;

        }       
    }
   
    public void removePerson(String name)
    {
        Person person = findPerson(name);  
        if(person != null){
            boolean ok = persons.remove(person);
            if(ok){
                System.out.println("Person " + name + "is removed from adressbook");
            }
            else{
            System.out.println("Its not possible to delete the person");
            }
        }
        else{ 
            System.out.println("There doesnt exits any persons with the name" + name + " in the addressbook");
        }
    }
    public Person getPerson(int id)
    {
        Person person = null;      
        int index = 0;     
        boolean found = false; 
        while(index < persons.size() && !found)
        {
            person = persons.get(index); 
            if(person.getId()==(id))
            {
                found = true;
            }
            else{
                 index++;  
                }
         } 
        if (found){
            return persons.get(index);
        }
        else{   
            System.out.println ("Not found");
            return null;
        }    
        
    }
    public int findPersonOnId(String name)
    {
        Person person = null;      
        int index = 0;     
        boolean found = false; 
        while(index < persons.size() && !found)
        {
            person = persons.get(index); 
            if(person.getName().equals(name))
            {
                found = true;
            }
            else{
                 index++;  
                }
         } 
        if (found){
            return persons.get(index).getId();
        }
        else{   
         return -1;

        }       
    }
    


                
            
    @SuppressWarnings("unchecked")
      public void readFromFile(String fileName) throws IOException, ClassNotFoundException {
        URL resource = getClass().getResource(fileName);
        //Determine if the dfault path can be obtained
        if (resource == null)
            throw new ClassNotFoundException(fileName);
            
        try {
            File source = new File(resource.toURI());
            ObjectInputStream is = new ObjectInputStream(new FileInputStream(source));
            persons = (ArrayList<Person>)is.readObject();    
            is.close();
        }
        catch(URISyntaxException e) {
            //make the exception more general
            throw new IOException("Cannot make the file " + fileName);  
        }
        
      }
    
     public void writeToFile(String fileName) throws IOException {
        URL resource = getResource(fileName);
        File destination = makeAbsoluteFilename(fileName);
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(destination));
        os.writeObject(persons);
        os.close();
    }
    
    private File makeAbsoluteFilename(String filename) throws IOException
    {
        try {
            File file = new File(filename);
            if(!file.isAbsolute()) {
                file = new File(getProjectFolder(), filename);
            }
            return file;
        }
        catch(URISyntaxException e) {
            throw new IOException("Unable to make a valid filename for " + filename);
        }
    }

    private File getProjectFolder() throws URISyntaxException
    {
        String myClassFile = getClass().getName() + ".class";
        URL url = getResource(myClassFile);
        return new File(url.toURI()).getParentFile();
    }
    
    private URL getResource(String fileName) {
        return getClass().getResource(fileName); 
    }
       
    
    
    
    
    
}
